#include "speech_server/comminucationhandler.hpp"
#include "speech_server/XmlProccessor.h"
ComminucationHandler::ComminucationHandler(int _port,QHostAddress _address,QObject *parent) :
    QThread(parent),mutex(new QMutex),socket(new QUdpSocket()),ports()
{
    address=_address;
    port=_port;
    assignPorts();
    socket->bind(port,QUdpSocket::ShareAddress);
}
void ComminucationHandler::assignPorts()
{
    ports["SpeechServer"]       =   SPEECHSERVER_PORT;
    ports["RemoteController"]   =   REMOTECONTROLL_PORT;
    ports["SpeechLogs"]         =   LOG_PORT;
}
void ComminucationHandler::run()
{
    working=true;
    qDebug()<<"Comunication handler has started to proccess";
    while(working)
    {
            if(socket->hasPendingDatagrams())
            {
                mutex->lock();

                //socket->waitForReadyRead();
                QByteArray *data=new QByteArray();
                while(socket->hasPendingDatagrams())
                {
                    data->resize(socket->pendingDatagramSize());
                    socket->readDatagram(data->data(),data->size());
                }
                ResultMessage r_message=XmlProccessor::ExtractContent(QString(data->data()));
                Q_EMIT MessageRecieved(r_message.Target,r_message.Content);
                //qDebug()<<"Message Recieved"<<r_message.Content;
                delete data;
                mutex->unlock();

            }
               QThread::msleep(1);

        }
    exec();
 }

void ComminucationHandler::sendCommand(QString target,QString command)
{
    mutex->lock();
    {
        //qDebug()<<"Sending Command: "<<command;
        socket->writeDatagram(command.toAscii(),command.size(),address,ports[target]);
    }
    mutex->unlock();
}
void ComminucationHandler::stop()
{
    working=false;
    quit();
    wait();
}
